package cn.itrip.trade.controller;

import cn.itrip.beans.dto.Dto;
import cn.itrip.beans.pojo.ItripHotelOrder;
import cn.itrip.common.DtoUtil;
import cn.itrip.trade.config.WXPayConfig;
import cn.itrip.trade.service.OrderService;
import cn.itrip.trade.wx.WXPayConstants;
import cn.itrip.trade.wx.WXPayRequest;
import cn.itrip.trade.wx.WXPayUtil;
import io.swagger.annotations.ApiOperation;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


@Controller
@RequestMapping("/api/wxpay")
public class WxPaymentController {

    private Logger logger = Logger.getLogger(WxPaymentController.class);

    @Autowired
    private OrderService orderService;

    @Autowired
    private WXPayConfig wxPayConfig;

    @ApiOperation(value = "订单微信支付", httpMethod = "GET",
            protocols = "HTTP", produces = "application/xml", consumes = "application/x-www-form-urlencoded",
            response = String.class,
            notes = "客户端提交订单支付请求，对该API的返回结果不用处理，" +
                    "浏览器将自动跳转至微信支付二维码页面。<br><b>请使用普通表单提交，" +
                    "不能使用ajax异步提交。</b>")
    @RequestMapping(value = "/createqccode/{orderNo}", method = RequestMethod.GET)
    @ResponseBody
    public Dto createQcCode(@PathVariable String orderNo, HttpServletResponse response) {
        //1.构造参数
        ItripHotelOrder order = null;
        try {
            order = orderService.hotelOrder(orderNo);
            Map<String, String> data = new HashMap<String, String>();
            data.put("body", "微信支付");
            data.put("out_trade_no", orderNo);
            data.put("device_info", "");
            data.put("fee_type", "CNY");
            data.put("total_fee", "1");
            data.put("spbill_create_ip", "123.12.12.123");
            Map<String, String> resultMap = new WXPayRequest(wxPayConfig).unifiedorder(data);
            if (resultMap.get("return_code").equals("SUCCESS") && resultMap.get("result_code").equals("SUCCESS")) {
                Map<String, String> result = new HashMap<>();
                result.put("payAmount", order.getPayAmount().toString());
                result.put("codeUrl", resultMap.get("code_url"));
                return DtoUtil.returnDataSuccess(result);
            } else {
                return DtoUtil.returnFail(resultMap.get("return_msg"), "100002");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return DtoUtil.returnFail("发生错误", "100001");
    }

    @RequestMapping(value = "/notify", method = RequestMethod.POST)
    public void paymentCallBack(HttpServletRequest request, HttpServletResponse response) {
        //1.从request获取XML流 转化为map数据
        try {
            StringBuilder stringBuilder = new StringBuilder();
            InputStream inputStream = request.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            String temp;
            while ((temp = reader.readLine()) != null) {
                stringBuilder.append(temp);
            }
            reader.close();
            inputStream.close();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(stringBuilder.toString());
            boolean flag = WXPayUtil.isSignatureValid(resultMap, wxPayConfig.getKey(), WXPayConstants.SignType.HMACSHA256);
            if (flag) {
                if (resultMap.get("return_code").equals("SUCCESS") && resultMap.get("result_code").equals("SUCCESS")) {
                    String out_trade_no = resultMap.get("out_trade_no");
                    String trade_no = resultMap.get("trade_no");
                    this.orderService.paySuccess(out_trade_no, 2, trade_no);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String, String> returnMap = new HashMap<>();
        returnMap.put("return_code", "SUCCESS");
        returnMap.put("return_msg", "SUCCESS");
        try {
            String respXml = WXPayUtil.generateSignedXml(returnMap, wxPayConfig.getKey(), WXPayConstants.SignType.HMACSHA256);

            response.getWriter().write(respXml);

            response.getWriter().flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //2.识别是否成功 修改订单状态
        //3.给微信返回结果
    }

    /**
     * 微信支付轮询订单，查看订单是否支付成功
     *
     * @param orderNo
     * @return
     */

    @ApiOperation(value = "订单微信支付刷单程序", httpMethod = "GET",
            protocols = "HTTP", produces = "application/xml", consumes = "application/x-www-form-urlencoded",
            response = String.class,
            notes = "前端用户检测订单是否成功的接口<br>如果订单状态为2则代表订单支付成功<b></b>")
    @RequestMapping(value = "/queryorderstatus/{orderNo}", method = RequestMethod.GET)
    @ResponseBody
    public Dto<ItripHotelOrder> queryOrderIsSuccess(@PathVariable String orderNo) {
        try {
            ItripHotelOrder order = orderService.hotelOrder(orderNo);
            return DtoUtil.returnDataSuccess(order);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return DtoUtil.returnFail("查询失败", "100003");
    }
}
